/**
 * @ngdoc module
 * @name email.controllers
 * @description
 *   邮件中心模块控制器
 */
angular.module('email.controllers', [])

  .controller('EmailIndexCtrl',function($ionicLoading, User, Utils){
    $ionicLoading.show();
    User.getAuthority().success(function(res){
      if(res.isSuccess){
        if(!res.data.email){
          Utils.promptNoPermission();
        }
      }
    }).finally($ionicLoading.hide)
  })

  .controller('EmailListCtrl', function($scope, $rootScope, $state, $ionicLoading, $ionicActionSheet, Email) {
    $scope.prop = {};

    // 初始化列表，首次进来时自动加载数据
    $scope.init = function() {
      // 若没有页面缓存，重置查询条件，直接加载第一页的数据
      if(!$scope.list.hasMails()) {
        $scope.list.refresh();
      }
    };

    // 刷新列表
    $scope.refresh = function() {
      $scope.prop.keyword = '';
      $scope.list.refresh()
        .finally(function() {
          $scope.$broadcast('scroll.refreshComplete');
        })
    };

    // 移动邮件至回收站
    $scope.remove = function(mail) {
      Email.remove(mail.emailid);
    };

    $scope.reply = function(mail) {
      $state.go('email.create', { id: mail.emailid, type: 'reply' });
      return true;
    };

    $scope.forward = function(mail) {
      $state.go('email.create', { id: mail.emailid, type: 'forward' });
      return true;
    };

    $scope.actionButtons = [
      {
        text: '转发',
        handler: function(mail) {
          return $scope.forward(mail);
        }
      },
      {
        text: '回复',
        handler: function(mail) {
          return $scope.reply(mail);
        }
      }
    ];

    $scope.showMenu = function(mail) {
      $scope.hideMenu = $ionicActionSheet.show({
        titleText: '邮件操作',
        buttons: $scope.actionButtons,
        buttonClicked: function(index, opts) {
          return opts.handler.call(null, mail);
        },
        destructiveText: '删除',
        destructiveButtonClicked: function() {
          $scope.remove(mail);
          return true;
        },
        cancelText: '取消'
      });
    };

    $scope.sref = 'email.detail({ id: mail.emailid })';

  })

/**
 * @ngdoc controller
 * @name EmailInboxCtrl
 * @module email.controllers
 * @description
 *   收件箱页控制器
 */
  .controller('EmailInboxCtrl', function($scope, $controller, Settings, EmailList, EmailInbox) {

    $controller('EmailListCtrl', { $scope: $scope });
    $scope.list = EmailInbox;
    $scope.title = '收件箱';
    $scope.init();

  })

/**
 * @ngdoc controller
 * @name EmailTodoCtrl
 * @module email.controllers
 * @description
 *   待办邮件列表页控制器
 */
  .controller('EmailTodoCtrl', function($scope, $controller, EmailTodo) {

    $controller('EmailListCtrl', { $scope: $scope });
    $scope.list = EmailTodo;
    $scope.title = '待办邮件';
    $scope.init();

  })

/**
 * @ngdoc controller
 * @name EmailOutboxCtrl
 * @module email.controllers
 * @description
 *   已发送列表页控制器
 */
  .controller('EmailOutboxCtrl', function($scope, $rootScope, $controller, EmailOutbox, Email) {

    $controller('EmailListCtrl', { $scope: $scope });
    $scope.list = EmailOutbox;
    $scope.title = '已发送';
    $scope.init();

    $scope.sref = 'email.outboxDetail({ id: mail.emailid })';

    // 重写列表删除邮件方法，已发送删除邮件为彻底删除，不移到回收站
    $scope.remove = function(mail) {
      Email.removeCompletelyConfirm(function() {
        Email.removeOutbox(mail.emailid)
      });
    }

  })

/**
 * @ngdoc controller
 * @name EmailTrashCtrl
 * @module email.controllers
 * @description
 *   已删除列表页控制器
 */
  .controller('EmailTrashCtrl', function($scope, $rootScope, $state, $controller, $ionicHistory, EmailTrash, Email) {

    $controller('EmailListCtrl', { $scope: $scope });
    $scope.list = EmailTrash;
    $scope.title = '已删除';
    $scope.init();

    $scope.sref = 'email.trashDetail({ id: mail.emailid })';

    // 替换 ActionSheet 菜单项
    $scope.actionButtons[1] = {
      text: '还原',
      handler: function(mail) {
        return $scope.recovery(mail);
      }
    };

    // 重写列表删除邮件方法，回收站删除将彻底删除邮件
    $scope.remove = function(mail) {
      Email.removeCompletelyConfirm(function() {
        Email.removeCompletely(mail.emailid)
      });
    }

    $scope.recovery = function(mail) {
      Email.recovery(mail.emailid);
      $ionicHistory.clearCache(['email.inbox', 'email.todo', 'email.trash'])
      return true;
    }
  })

/**
 * @ngdoc controller
 * @name EmailDetailCtrl
 * @module email.controllers
 * @description
 *   查看邮件页控制器
 */
  .controller('EmailDetailCtrl', function($scope, $rootScope, $state, $stateParams, $sce, $filter, $ionicHistory, $ionicLoading, Email, EmailUtils) {
    $ionicLoading.show();

    Email.get($stateParams.id)
      .success(function(res) {
        $scope.mail = res;

        // 判断返回的内容为可信 html 以保留样式
        if($scope.mail.content) {
          $scope.mail.content = $sce.trustAsHtml( $filter('editorContent')($scope.mail.content) );
        }
      })
      .finally($ionicLoading.hide);

    // 删除邮件
    $scope.remove = function() {
      Email.remove($scope.mail.emailid)
        .success(function(res) {
          if(res.isSuccess) {
            EmailUtils.goBackOrHome();
          }
        });
    };

    // 待办、取消待办
    $scope.toggleMark = function() {
      var mark = $scope.mail.ismark != '1';

      Email.mark($scope.mail.emailid, mark)
        .success(function(res) {
          $scope.mail.ismark = +mark + '';
          $ionicHistory.clearCache(['email.inbox', 'email.outbox', 'email.todo', 'email.trash'])
        })
    };

    $scope.reply = function() {
      $state.go('email.create', { id: $scope.mail.emailid, type: 'reply' });
    };

    $scope.replyAll = function() {
      $state.go('email.create', { id: $scope.mail.emailid, type: 'replyAll' });
    };
  })

/**
 * @ngdoc controller
 * @name EmailTrashDetailCtrl
 * @module email.controllers
 * @description
 *   已删除-查看邮件详细页控制器
 */
  .controller('EmailTrashDetailCtrl', function($scope, $controller, Email, EmailUtils, $ionicLoading) {
    $controller('EmailDetailCtrl', { $scope: $scope });

    $scope.remove = function() {
      Email.removeCompletelyConfirm(function() {
        $ionicLoading.show();
        Email.removeCompletely($scope.mail.emailid)
          .success(function(res) {
            if(res.isSuccess) {
              EmailUtils.goBackOrHome();
            }
          })
          .finally($ionicLoading.hide);
      });
    }
  })

/**
 * @ngdoc controller
 * @name EmailOutboxDetailCtrl
 * @module email.controllers
 * @description
 *   已发送-查看邮件详细页控制器
 */
  .controller('EmailOutboxDetailCtrl', function($scope, $ionicLoading, $rootScope, $controller, $state, Email, EmailUtils) {
    $controller('EmailDetailCtrl', { $scope: $scope });

    $scope.remove = function() {
      Email.removeCompletelyConfirm(function() {
        $ionicLoading.show();
        Email.removeOutbox($scope.mail.emailid)
          .success(function(res) {
            if(res.isSuccess) {
              EmailUtils.goBackOrHome();
            }
          })
          .finally($ionicLoading.hide);
      });
    }
  })

/**
 * @ngdoc controller
 * @name EmailCreateCtrl
 * @module email.controllers
 * @description
 *   写邮件页控制器
 */
  .controller('EmailCreateCtrl', function($scope, $rootScope, $sce, $filter, $timeout, $state, $stateParams, $ionicLoading, $ionicHistory, Email, EmailUtils) {

    $scope.form = {
      toids: '',
      ccids: '',
      mcids: '',
      subject: '',
      content: ''
    };

    $scope.isSubmitting = false;

    // 设置源邮件信息
    function setSource(res) {
      $scope.source = res;

      // 回复
      if($stateParams.type == 'reply') {
        $scope.form.toids = res.fromid;
        $scope.form.subject = '回复：' + res.subject;

        // 回复全部（发件人、所以收件人及抄送人）
      } else if($stateParams.type == 'replyAll') {
        $scope.form.toids = EmailUtils.concatToids(res.fromid, res.toids, res.copytoids);
        $scope.form.subject = '回复：' + res.subject;

        // 转发
      } else if($stateParams.type == 'forward') {
        $scope.form.subject = '转发：' + res.subject;
        $scope.form.attachmentid = res.attachmentid;
      }

      if(res.content) {
        $scope.source.content = $sce.trustAsHtml( $filter('editorContent')(res.content) );
      }
    }

    // 如果有 url 参数 id 和 type，判断此时为回复或转发邮件
    if($stateParams.id && $stateParams.type) {
      $ionicLoading.show();
      Email.get($stateParams.id)
        .success(setSource)
        .finally($ionicLoading.hide)
    }

    $scope.showOther = function() {
      $scope.isShowOther = true;
    }

    // 表单提交中或表单未通过验证时，禁止提交
    $scope.isDisabledSubmit = function() {
      return $scope.isSubmitting || !$scope.emailForm.$valid;
    };

    $scope.submit = function() {
      $scope.isSubmitting = true;
      $ionicLoading.show();

      // 如果有原邮件（回复、转发的情况），则组合内容
      var formData = angular.extend({}, $scope.form, {
        content: $scope.source ?
        $scope.form.content + document.getElementById('email_info').innerHTML + $scope.source.content :
          $scope.form.content
      })

      Email.create(formData)
        .success(function() {
          $ionicHistory.clearCache(['email.inbox', 'email.outbox']);
          EmailUtils.showSendedPopup($scope);
        })
        .finally($ionicLoading.hide);
    }

  })
